package cn.wolfcode.interceptor;

import cn.wolfcode.annotation.RequiredPermission;
import cn.wolfcode.domain.Permission;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

public class MyPermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //自定义拦截功能 只满足拦截器的过滤要求 就需在这个自定义拦截器中过滤一下
        HttpSession session = request.getSession();
        List<Permission> permissions = (List<Permission>) session.getAttribute("userpermission");
        List<String> expressions = new ArrayList<>();
        if (permissions != null) {
            for (Permission permission : permissions) {
                expressions.add(permission.getExpression());
            }

            //获取当前模块的方法  非方法就放行
            if (!(handler instanceof HandlerMethod)) {
                return true;
            }

            //只对控制器中的方法进行验证
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RequiredPermission ann = handlerMethod.getMethodAnnotation(RequiredPermission.class);
            if (ann == null) {
                return true;
            } else {
                //得到方法上的权限表达式
                String expression = ann.experssion();
                //判断登陆者所拥有的权限 与某一个方法上的权限是否相等 来确定该用户是否有访问该方法的权限
                if (expressions.contains(expression)){
                    return true;
                }else {
                    request.getRequestDispatcher("/WEB-INF/views/common/nopermission.ftl").forward(request,response);
                    return false;
                }
            }
        }
        return false;
    }
}
